var createError = require('http-errors');
var express=require('express');
var app = express();
var server=require('http').Server(app);
var io = require('socket.io')(server);
app.set('view engine', 'ejs');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');


var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lm');

//链接状态
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {

});


var UserSchame=mongoose.Schema({

    nickName:String,
    userTag:String,
    userFace:String,
    passWord:String,
});


var ChatShame=mongoose.Schema({

    nickName:String,
    userFace:String,
    chatContent:String,
    createTime:String
});

var TopicShame=mongoose.Schema({

    nickName: String,
    userFace:String,
    topicContent:String,
    createTime:String,
    posterTime:String,
    isSelected:{type:String,default:"false"}
});

var User=mongoose.model("lmusers",UserSchame);//个人信息
var Chat=mongoose.model("lmchat",ChatShame);//聊天信息
var Topic=mongoose.model("topic",TopicShame);//话题信息

server.listen(8002);

app.set('views', path.join(__dirname, 'views'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

io.on('connection',function (socket) {



    socket.on('sendmsg', function(msg){



        let currentName=msg.nickname;
        let currentFace=msg.userface;
        let currentchatContent=msg.chatcontent;
        let currentData=msg.createtime;

        let chatitem=new Chat({

            nickName:currentName,
            userFace:currentFace,
            chatContent:currentchatContent,
            createTime:currentData,
        });

        chatitem.save(function (err) {

            if(!err){

                socket.broadcast.emit("send",msg);
                console.log(msg);
            }
        });

    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });

});


//用户注册
app.post("/toSign",function (req,res) {

    let target=req.query;
    let number=target.num;
    let password=target.pass;
    let nickname=target.nick;
    if((number.length>=6&&number.length<18)&&(password.length>=6&&password.length<16)) {
        User.findOne({userTag: number}, function (err, doc) {

            if (err) {

                return;
            } else {

                if (doc == null) {


                    var newUser = new User({

                        nickName: nickname,
                        userTag: number,
                        userFace: "/images/face1.jpg",
                        passWord:password
                    });

                    newUser.save(function (err) {

                        if (err) {

                            return;
                        } else {

                            res.cookie("userInfo",{user:number,nick:nickname,face:"/images/face1.jpg"});
                            res.json({result:{
                                    nickName: nickname,
                                    userTag: number,
                                    userFace: "/images/face1.jpg"
                                 }});
                        }
                    });

                }else{

                    //已经被注册
                    return;
                }

            }
        })
    }

});

//用户登录
app.post("/toLogin",function (req,res) {

    let target=req.query;
    let number=target.num;
    let password=target.pass;
    User.findOne({userTag:number},function (err,data) {

        if(err){


            return
        }else {

            if(data!=null){

                res.cookie("userInfo",{user:number,nick:data.nickName,face:data.userFace});
                if(data.passWord==password){

                 res.json({result:data});

                }
            }

        }
    })

});

//更新face
app.get("/updateFace",function (req,res) {

    let newface=req.query.url;
    let nickname=req.query.nick;
    if(newface!=""){
     User.update({nickName:nickname},{userFace:newface},function (err) {

         if(err){
             return;
         }else {

             res.json({result:"OK"});
         }
     });

    }
});


app.get("/cleanIt",function (req,res){

   Chat.remove({},function (err) {

       if(err){


       }else {


           res.json({status:"OK"});
       }
   });

});

app.get("/cleanIttop",function (req,res){

    Topic.remove({},function (err) {

        if(err){


        }else {


            res.json({status:"OK"});
        }
    });

});

app.get("/selectTop",function (req,res){

    var nick=req.query.nick;

   Topic.update({nickName:nick},{isSelected:"true"},function (err) {

       if(err){

       }else{
           res.json({status:"OK"});
       }
   });

});


//提交话题
app.post("/postTopic",function (req,res) {

    let data=req.query;
    let userFace=data.userface;
    let userNick=data.nickname;
    let topicContent=data.topiccontent;
    let createTime=data.createtime;
    console.log(data);
    if(topicContent.length>6&&topicContent.length<=200){

        Topic.findOne({nickName:userNick},function (err,data) {

           if(err){


           } else {

               if(data!=null){

                   res.json({status:"BEEN"});
                   return;
               }else{

                   let topicitem=new Topic({

                       nickName: userNick,
                       userFace:userFace,
                       topicContent:topicContent,
                       createTime:createTime
                   });

                   topicitem.save(function (e) {

                       if(e){

                           res.json({status:"NO"});
                           return;
                       }else {

                        res.json({status:"OK"});
                        return;

                       }
                   });
               }
           }

        });

    }

});


app.get("/gettimelineInfo",function (req,res) {


    Chat.find({},function (err,data) {

        if(err){

            return;
        }else {
            res.json(data);
        }
    });
});

//获取话题
app.get("/getTopic",function (req,res) {


    Topic.findOne({isSelected:"true"},function (err,data) {

        if(err){

            return;

        }else {

            if(data!=null){

                res.json({data});
            }else{

                //还没产生话题
                res.json({status:"NONE"});
            }
        }
    });

});



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;